<?php 
namespace town\base;

class Response
{
    private static $obj = null;

    private $header = null;

    private $content = null;

    public function __construct()
    {
        ob_start();
        static::$obj = $this;
        $this->header = ["Content-type:text/html;charset=utf-8"];
    }


    /**
     * 处理头
     */
    public function header($header)
    {
        $this->header[] = $header;
        return $this;
    }


    /**
     * 中断处理
     */
    public function abort($code = 200)
    {
        http_response_code($code);
        exit();
    }


    /**
     * 重定向
     */
    public function redirect($url = '', $abs = false)
    {
        if ($abs == false) {
            $url = $_SERVER['SERVER_HOST'].'/'.ltrim($url, '/');
        }
        $this->header[] = 'Location: '.$url;
        $this->send();
        exit();
    }


    /**
     * 返回html代码内容
     * $datas 1.为数组时,是赋值 2.为string则为取缓存
     */
    public function view($name, $datas = [])
    {
        return view($name, $datas);
    }


    /**
     * 内容
     */
    public function content($content = '')
    {
        $this->content = $content;
        return $this;
    }


    /**
     * 返回json内容
     */
    public function json($data)
    {
        $this->content = json_encode($data);
        return $this;
    }


    /**
     * 处理cookie
     */
    public function cookie($name, $value)
    {
        setcookie($name,$value,$expire,$path,$domain,$secure);
        return $this;
    }


    /**
     * 构建头信息
     */
    private function buildHeader()
    {
        foreach ($this->header as $val) {
            header($val);
        }
    }


    /**
     * 构建内容
     */
    public function buildContent()
    {
        return $this->content;
    }


    /**
     * 输出信息
     */
    public function send()
    {
        $this->buildHeader();
        echo $this->buildContent();
        ob_end_flush();
    }


    /**
     * 析构函数
     */
    public function __destruct()
    {
        if (ob_get_length() > 1) {
            ob_end_flush();
        }
    }

    public function __call($method, $arguments)
    {
        if (method_exists($this, $method)) {
            return call_user_func_array([$this, $method], $arguments);
        }
    }
    
    public static function __callStatic($method, $arguments)
    {
        $obj = static::singleton();
        if (method_exists($obj, $method)) {
            return call_user_func_array([$obj, $method], $arguments);
        }
    }

    public static function singleton()
    {
        if (static::$obj == null) {
            static::$obj = new static();
        }
        return static::$obj;
    }

}